package org.smallreunion.controller.admin;

import java.util.HashMap;
import java.util.Map;

import org.slim3.controller.Controller;
import org.slim3.controller.Navigation;
import org.smallreunion.exception.ConfigRuntimeException;
import org.smallreunion.model.config.TwitterConfig;
import org.smallreunion.model.constract.CounterShardType;
import org.smallreunion.service.ConfigService;
import org.smallreunion.service.CounterShardService;

/**
 * 管理者用トップページ
 * @author Sinmetal
 *
 */
public class IndexController extends Controller {

    private ConfigService configService = new ConfigService();

    private CounterShardService counterService = new CounterShardService();

    /**
     * 管理者用トップページ表示
     */
    @Override
    public Navigation run() throws Exception {
        TwitterConfig twitterConfig = getTwitterConfig();
        requestScope("twitterConsumerKey", twitterConfig.getConsumerKey());
        requestScope("twitterConsumerSecret", twitterConfig.getConsumerSecret());

        requestScope("counter", getCounter());
        return forward("index.jsp");
    }

    /**
     * TwitterConfig取得
     *
     * @return
     */
    private TwitterConfig getTwitterConfig() {
        TwitterConfig config;
        try {
            config = configService.getTwitterConfig();
        } catch (ConfigRuntimeException e) {
            config = new TwitterConfig();
            config.setConsumerKey("設定無し");
            config.setConsumerSecret("設定無し");
        }

        return config;
    }

    /**
     * 全てのカウンターのカウント数を取得
     *
     * @return
     */
    private Map<CounterShardType, Integer> getCounter() {
        Map<CounterShardType, Integer> resultMap = new HashMap<CounterShardType, Integer>();
        for (CounterShardType type : CounterShardType.values()) {
            int count = counterService.getCount(type);
            resultMap.put(type, count);
        }
        return resultMap;
    }
}
